<?php

namespace app\merchants\controller;

use app\common\validate\merchant\MerchantDepartmentValid;
use app\common\validate\merchant\MerchantRolesValid;
use app\common\validate\merchant\MerchantValid;
use app\merchants\loader\Services;
use think\Exception;

/**
 * 商户管理
 */
class Merchant extends ApiBase
{
    /**
     * 登录
     */
    public function login(): void
    {
        $postData = $this->request->post();
        try {
            $this->validate($postData, MerchantValid::class . '.login');
            $authData = Services::Merchant()->login($postData['username'], $postData['passwd'], $postData['key'], $this->request_app);
            api_result(API_SUCCESS, '登录成功', $authData);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 菜单列表
     */
    public function group_menu()
    {
        try {
            $list = Services::MerchantRole()->getMerchantMenu($this->adminUser);
            api_result(API_SUCCESS, '请求成功', $list);
        } catch (Exception $exception) {
            api_result($exception);
        }
    }

    /**
     * 当前用户权限列表
     * @throws Exception
     */
    public function group_permission()
    {
        $action = Services::MerchantRole()->getMerchantMenu($this->adminUser, false);
        if (!empty($action)) {
            api_result(API_SUCCESS, '请求成功', $action);
        }
        api_result(API_ERROR, '未分配权限，请联系管理员');
    }

    /**
     * 商户列表 分页
     */
    public function page()
    {
        try {
            $option = $this->makeMerchantWhere();
            $result = Services::Merchant()->getPage($option);
            api_result($result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 根据请求,生成条件
     * @return array
     */
    private function makeMerchantWhere(): array
    {
        $params = $this->request->get();
        $options = $this->formatOption($params);
        $where[] = ['mer_id', '=', $this->adminUser['mer_id']];
        if (!empty($params['keyword'])) {
            $where[] = ['username|mobile', 'like', "%" . trim($params['keyword']) . "%"];
        }
        // 角色组ID
        if (!empty($params['group_id'])) {
            $where[] = ['role_id', '=', $params['group_id']];
        }
        // 部门ID
        if (!empty($params['dept_id'])) {
            $where[] = ['dept_id', '=', $params['dept_id']];
        }
        if (!empty($this->adminUser['sub_admin_ids'])) {
            $where[] = ['id', 'in', $this->adminUser['sub_admin_ids']];
        }
        if (isset($params['status']) && $params['status'] !== '') {
            $where[] = ['status', '=', $params['status']];
        }
        $options['where'] = $where;
        return $options;
    }

    /**
     * 微信解绑
     * @return void
     */
    public function save_oauth(): void
    {
        $param = input('post.');
        try {
            $this->validate($param, MerchantValid::class . '.save_oauth');
            $where = [
                'mer_id' => $this->adminUser['mer_id'],
                'id' => (int)$param['admin_id']
            ];
            Services::Merchant()->saveOauth($where);
            api_result(API_SUCCESS, '请求成功');
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 商户列表
     */
    public function list()
    {
        try {
            $option = $this->makeMerchantWhere();
            $result = Services::Merchant()->getList($option);
            api_result($result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 编辑商户
     */
    public function save()
    {
        $params = $this->request->post();
        try {
            $params['mer_id'] = $this->adminUser['mer_id'];
            $params['op_user'] = $this->adminUser['admin_id'];
            $scene = '.add';
            if (!empty($params['id'])) {
                unset($params['op_user']);
                $scene = '.edit';
            }
            $this->validate($params, MerchantValid::class . $scene);
            $result = Services::Merchant()->saveMerchant($params);
            api_result(API_SUCCESS, '保存成功', ['id' => $result]);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 商户详情
     */
    public function info()
    {
        $id = $this->request->get('id');
        try {
            if (empty($id)) {
                api_exception(API_ERROR, '商户ID不能为空');
            }
            $option['where'] = [['id', '=', $id], ['mer_id', '=', $this->adminUser['mer_id']]];
            $result = Services::Merchant()->getInfo($option);
            api_result($result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 删除商户
     */
    public function del()
    {
        $id = $this->request->post('id');
        try {
            if (empty($id)) {
                api_exception(API_ERROR, '商户ID不能为空');
            }
            $where = [['id', '=', $id], ['mer_id', '=', $this->adminUser['mer_id']]];
            Services::Merchant()->delMerchant($where);
            api_result([]);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 设置商户状态
     */
    public function edit_status()
    {
        $params = $this->request->post();
        try {
            $this->validate($params, MerchantValid::class . '.edit_status');
            Services::Merchant()->saveMerchant($params);
            api_result(API_SUCCESS, "保存成功");
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 修改密码
     */
    public function edit_password()
    {
        $params = $this->request->post();
        try {
            $this->validate($params, MerchantValid::class . '.reset_pass');
            $res = Services::Merchant()->editPassword((int)$this->adminUser['admin_id'], $params['oldpasswd'], $params['password'], (int)$this->request_app);
            api_result($res);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 部门列表分页
     */
    public function dept_page()
    {
        $params = $this->request->get();
        try {
            $option = $this->formatOption($params);
            $where[] = ['mer_id', '=', $this->adminUser['mer_id']];
            if (!empty($params['keyword'])) {
                $where[] = ['title', 'like', "%" . $params['keyword'] . "%"];
            }
            if (isset($params['pid']) && $params['pid'] !== '') {
                $where[] = ['pid', '=', $params['pid']];
            }
            if (!empty($this->adminUser['sub_admin_ids'])) {
                $where[] = ['op_user', 'in', $this->adminUser['sub_admin_ids']];
            }
            $option['where'] = $where;
            $result = Services::MerchantDepartment()->getPage($option);
            api_result($result);
        } catch (Exception $e) {
            api_result($e);
        }

    }

    /**
     * 部门添加编辑
     */
    public function dept_save()
    {
        $params = $this->request->post();
        try {
            $params['mer_id'] = $this->adminUser['mer_id'];
            $params['op_user'] = $this->adminUser['admin_id'];
            $params['is_sys'] = 0;
            $scene = '.create';
            if (!empty($params['id'])) {
                unset($params['op_user']);
                $scene = '.edit';
            }
            $this->validate($params, MerchantDepartmentValid::class . $scene);
            Services::MerchantDepartment()->saveDept($params);
            api_result(API_SUCCESS, '保存成功');
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 部门添加编辑
     */
    public function dept_save_sort()
    {
        $params = $this->request->post();
        try {
            $this->validate($params, MerchantDepartmentValid::class . '.edit_sort');
            Services::MerchantDepartment()->editDept(['id' => $params['id'], 'mer_id' => $this->adminUser['mer_id']], ['sort' => $params['sort']]);
            api_result(API_SUCCESS, '保存成功');
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 部门树形列表
     */
    public function dept_treelist()
    {
        try {
            $option = [];
            $option['where'][] = ['mer_id', '=', $this->adminUser['mer_id']];
            if (!empty($this->adminUser['sub_admin_ids'])) {
                $admin_id = $this->adminUser['sub_admin_ids'];
                $where[] = ['id', 'in', function ($query) use ($admin_id) {
                    $query->name('merchant')->whereIn('id', $admin_id)->field('dept_id');
                }];
                $option['where'][] = $where;
            }
            $result = Services::MerchantDepartment()->getList($option, 1);
            api_result($result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 部门详情
     */
    public function dept_info()
    {
        try {
            $id = $this->request->get('id');
            if (empty($id)) {
                api_exception(400, '部门ID不能为空');
            }
            $option['where'] = [['id', '=', $id], ['mer_id', '=', $this->adminUser['mer_id']]];
            $info = Services::MerchantDepartment()->getInfo($option);
            api_result($info);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 部门列表
     */
    public function dept_list()
    {
        try {
            $params = $this->request->get();
            $where[] = ['mer_id', '=', $this->adminUser['mer_id']];
            if (!empty($this->adminUser['sub_admin_ids'])) {
                $admin_id = $this->adminUser['sub_admin_ids'];
                $where[] = ['id', 'in', function ($query) use ($admin_id) {
                    $query->name('merchant')->whereIn('id', $admin_id)->field('dept_id');
                }];
                $option['where'][] = $where;
            }
            if (isset($params['pid']) && $params['pid'] !== '') {
                $where[] = ['pid', '=', $params['pid']];
            }
            $option['where'] = $where;
            $result = Services::MerchantDepartment()->getList($option, 0);
            api_result($result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 删除部门
     */
    public function dept_del()
    {
        try {
            $params = $this->request->post();
            if (empty($params['id'])) {
                api_exception(400, '部门ID不能为空');
            }
            Services::MerchantDepartment()->del($params['id'], $this->adminUser['mer_id']);
            api_result(API_SUCCESS, '删除成功');
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 角色组分页
     */
    public function role_page()
    {
        $params = $this->request->get();
        try {
            $option = $this->formatOption($params);
            $where[] = ['mer_id', '=', $this->adminUser['mer_id']];
            if (!empty($option['keyword'])) {
                $where[] = ['title', 'like', '%' . $option['keyword'] . '%'];
            }
            if (!empty($this->adminUser['sub_admin_ids'])) {
                $where[] = ['op_user', 'in', $this->adminUser['sub_admin_ids']];
            }
            $option['where'] = $where;
            $result = Services::MerchantRole()->getPage($option);
            api_result(API_SUCCESS, "请求成功", $result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 角色列表
     */
    public function role_list()
    {
        $params = $this->request->get();
        try {
            $allField = $params['flag'] ?? 0;
            $params['limit'] = $params['limit'] ?? 30;
            $option = $this->formatOption($params);
            $where[] = ['mer_id', '=', $this->adminUser['mer_id']];
            if (!empty($this->adminUser['sub_admin_ids'])) {
                $where[] = ['op_user', 'in', $this->adminUser['sub_admin_ids']];
            }
            if (!empty($option['keyword'])) {
                $where[] = ['title', 'like', '%' . $option['keyword'] . '%'];
            }
            $option['where'] = $where;
            $result = Services::MerchantRole()->getList($option, $allField);
            api_result(API_SUCCESS, "请求成功", $result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     *  角色组添加/修改
     */
    public function role_save()
    {
        $params = $this->request->post();
        try {
            $params['mer_id'] = $this->adminUser['mer_id'];
            $params['op_user'] = $this->adminUser['admin_id'];
            $params['is_sys'] = 0;
            $scene = '.create';
            if (!empty($params['id'])) {
                unset($params['op_user'], $params['is_sys']);
                $scene = '.edit';
            }
            $this->validate($params, MerchantRolesValid::class . $scene);
            Services::MerchantRole()->roleSave($params);
            api_result(API_SUCCESS, "保存成功");
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 角色信息
     */

    public function role_info()
    {
        try {
            $id = $this->request->get('id', 0);
            $info = Services::MerchantRole()->roleInfo(['where' => ['id' => $id, 'mer_id' => $this->adminUser['mer_id']]]);
            api_result($info);
        } catch (Exception $e) {
            api_result($e);
        }
    }


    /**
     * 删除组角色
     * @title 删除角色
     * @auth true
     */
    public function role_del()
    {
        try {
            $id = $this->request->post('id');
            if (empty($id)) {
                api_exception(400, '角色ID不能为空');
            }
            Services::MerchantRole()->roleDel($id, $this->adminUser['mer_id']);
            api_result(API_SUCCESS, "删除成功");
        } catch (Exception $e) {
            api_result($e);
        }
    }

}
